import signer from './signer'
const buildURL = require('axios/lib/helpers/buildURL');

export default {
    // 设置mse网关请求头
    setMseHeaders(config) {
        console.log(config, 'config')
        let body = '', url = ''
        let signedHeaders = {}
        if (config.data && config.headers['Content-Type'] !== 'multipart/form-data') {
            body = JSON.stringify(config.data)
        }
        if (config.headers['x-sdk-content-sha256']) {
            signedHeaders['x-sdk-content-sha256'] = config.headers['x-sdk-content-sha256']
        }
        if (config.params) {
            url = buildURL(config.url, config.params, config.paramsSerializer)
            url = decodeURIComponent(url).replace(/%2C/gi, ',') // %2c转成逗号 mse网关sdk需要转码之前的参数
        } else {
            url = config.url
        }

        var req = signer.HttpRequest(config.method.toLocaleUpperCase(), url, signedHeaders, body);

        console.log(req, 'req')
        var opt = signer.Sign(req);
        console.log(opt, 'opt')
        config.headers['X-Sdk-Date'] = opt.headers['X-Sdk-Date']
        config.headers['v587sign'] = opt.headers['v587sign']
        return config
    },
    // 删除值为undefined的字段 因为axios会默认干掉值为undefined的字段不会请求
    removeUndefinedProperty(obj) {
        Object.keys(obj).forEach(item => {
            if (obj[item] === undefined) delete obj[item]
        })
        return obj
    },
    // url后面拼接参数签名验证
    objectToQuery(obj) {
        // Query和Form参数为空时，则直接使用Path，不需要添加?(2)
        if (typeof obj !== "object") return "";
        const attrs = Object.keys(obj);
        return attrs.reduce((query, attr, index) => {
            if (obj[attr] === '' || obj[attr] === undefined) {
                // 参数的Value为空时只保留Key参与签名，等号需要再加入签名(3)
                // 判断是否是第一层第一个循环
                if (index === 0) {
                    query += `?${attr}=`;
                } else {
                    query += `&${attr}=`;
                }
            } else if (Array.isArray(obj[attr])) {
                if (obj[attr].length) {
                    obj[attr].forEach((item1, index1) => {
                        if (index === 0 && index1 === 0) {
                            query += `?${attr}=${obj[attr][0]}`;
                        } else {
                            query += `&${attr}=${obj[attr][index1]}`;
                        }
                    })
                }
            } else {
                if (index === 0) {
                    query += `?${attr}=${obj[attr]}`;
                } else {
                    query += `&${attr}=${obj[attr]}`;
                }
            }
            return query;
        }, "");
    },
}
